<template>
  <view class="layout">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="statusBar" :style="{ height: getStatusBarHeight() + 'px' }"></view>
      <view class="titleBar" :style="{ height: getTitleBarHeight() + 'px', marginLeft: getLeftIconLeft() + 'px' }">
        <view class="back">
          <uni-icons type="back" size="24" color="#333" @click="goBack"></uni-icons>
        </view>
        <view class="search-container">
          <view class="search-box">
            <uni-icons type="search" size="20" color="#999"></uni-icons>
            <input type="text" placeholder="输入书名/作者" class="search-input" v-model="searchInput" />
            <view class="clear-input" v-show="searchInput" @click="clearSearch">
              <uni-icons type="clear" size="20" color="#999"></uni-icons>
            </view>
          </view>
        </view>
        <view class="search-button">
          <text class="search-text" @click="handleSearch">搜索</text>
        </view>
      </view>
    </view>

    <!-- 填充区域 -->
    <view class="fill" :style="{ height: getNavBarHeight() + 'px' }"></view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="showSearchResults">
      <view class="book-item" v-for="(book, index) in searchResults" :key="index" @click="goRead(book)">
        <view class="book-cover">
          <image :src="book.image" class="cover-image"></image>
        </view>
        <view class="book-details">
          <view class="book-title-rating">
            <rich-text :nodes="highlightKeyword(book.novelName)"></rich-text>
            <text class="book-rating">{{ book.score }}分</text>
          </view>
          <rich-text :nodes="highlightKeyword(book.des)" class="book-description"></rich-text>
          <rich-text :nodes="highlightKeyword(`${book.author} · ${book.status} · ${book.name}`)" class="book-author"></rich-text>
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-section" v-else>
      <!-- 搜索框历史 -->
      <view class="search-history" v-if="searchHistory.length > 0">
        <view class="section-title">
          <text>搜索历史</text>
          <view class="clear-history">
            <uni-icons type="trash" size="20" color="#999" @click="clearHistory"></uni-icons>
          </view>
        </view>
        <view class="history-list">
          <view class="history-item" v-for="(history, index) in searchHistory" :key="index" @click="fillSearchInput(history)">
            <rich-text :nodes="highlightKeyword(history)"></rich-text>
          </view>
        </view>
      </view>

      <view class="hot-search">
        <view class="section-title">
          <text style="font-weight: bold;">热搜书籍</text>
          <view class="refresh-icon">
            <uni-icons 
              type="refresh" 
              size="20" 
              color="#999"
              :class="{ 'rotating': isRefreshing }"
              @click="refreshHotBooks"
            ></uni-icons>
          </view>
        </view>
        <view class="hot-books">
          <view class="book-item" v-for="(book, index) in hotBooks" :key="index" @click="read(book.novelId)">
            <view class="book-rank" :style="{ color: getRankColor(index) }">{{ index + 1 }}</view>
            <view class="book-cover">
              <image :src="book.image" class="cover-image"></image>
            </view>
            <view class="book-info">
              <view class="book-title">
                <rich-text :nodes="highlightKeyword(book.novelName)"></rich-text>
              </view>
              <text class="book-search-count">{{ book.searchCount }}次搜索</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from "@/utils/system.js";
import {ApiSearchNovel,ApigetHotSearch,ApiAddSearchCount } from "../api/novel.js";

// 搜索栏的值
const searchInput = ref("");

// 搜索结果数据
const searchResults = ref([]);

// 热搜书籍数据
const hotBooks = ref([]);

// 显示搜索结果
const showSearchResults = ref(false);

// 搜索文本历史（从缓存获取初始值）
const searchHistory = ref([]);

// 刷新状态
const isRefreshing = ref(false);
const pageNum = ref(1);
const size = ref(10);

// 初始化：从缓存加载搜索历史
onMounted(() => {
  const cachedHistory = uni.getStorageSync('searchHistory');
  if (cachedHistory && Array.isArray(cachedHistory)) {
    searchHistory.value = cachedHistory;
  }
  getHotSearch();
});

// 获取热搜数据
const getHotSearch = async() => {
  try {
    let res = await ApigetHotSearch(pageNum.value, size.value);
    hotBooks.value = res;
  } catch (error) {
    console.error('获取热搜数据失败', error);
    uni.showToast({
      title: '获取热搜数据失败',
      icon: 'none'
    });
  }
};

// 搜索处理
const handleSearch = async() => {
  const keyword = searchInput.value.trim();
  if (!keyword) {
    showSearchResults.value = false;
    return;
  }

  try {
    // 执行搜索
    const res = await ApiSearchNovel(keyword);
    searchResults.value = res || [];
    
    // 处理搜索历史（去重 + 最新前置 + 最多10条）
    const index = searchHistory.value.indexOf(keyword);
    if (index !== -1) {
      searchHistory.value.splice(index, 1); // 移除原有记录
    }
    searchHistory.value.unshift(keyword); // 新记录添加到顶部
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10); // 保留最多10条
    }

    // 保存到缓存
    uni.setStorageSync('searchHistory', searchHistory.value);

    // 显示搜索结果
    showSearchResults.value = true;
  } catch (error) {
    console.error('搜索失败', error);
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none'
    });
  }
};

// 清空搜索
const clearSearch = () => {
  searchInput.value = "";
  showSearchResults.value = false;
};

// 填充搜索框并触发搜索
const fillSearchInput = (value) => {
  searchInput.value = value;
  handleSearch();
};

// 清除搜索历史（包括缓存）
const clearHistory = () => {
  searchHistory.value = [];
  uni.removeStorageSync('searchHistory');
  uni.showToast({
    title: '已清空搜索历史',
    icon: 'success'
  });
};

// 刷新热搜书籍
const refreshHotBooks = () => {
  isRefreshing.value = true;
  pageNum.value += 1;
  getHotSearch().finally(() => {
    isRefreshing.value = false;
  });
};

// 获取排名颜色
const getRankColor = (index) => {
  if (index === 0) return "#FF5722";
  if (index === 1) return "#FF9800";
  if (index === 2) return "#FFEB3B";
  return "#333";
};

// 关键词高亮函数
const highlightKeyword = (text) => {
  if (!text || !searchInput.value.trim()) return text;
  
  // 创建正则表达式，全局匹配且不区分大小写
  const keyword = searchInput.value.trim();
  const regExp = new RegExp(keyword, 'gi');
  
  // 使用正则表达式替换匹配到的关键词为红色加粗文本
  return text.replace(regExp, match => `<span style="color: #FF4444; font-weight: bold;">${match}</span>`);
};

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 跳转到阅读页面
const goRead = async(val) => {
  uni.navigateTo({
    url: `/pages/novel/bookCover?bookId=${val.novelId}`
  });
  //更新搜索次数
  await ApiAddSearchCount(val.novelId)
};

// 跳转到阅读页面
const read = async(val) => {
  uni.navigateTo({
    url: `/pages/novel/bookCover?bookId=${val}`
  });
  //更新搜索次数
  await ApiAddSearchCount(val)
};
</script>

<style lang="scss" scoped>
.layout {
  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
    background: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .statusBar {
      background: #fff;
    }

    .titleBar {
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      height: 44px;
    }

    .back-icon {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16rpx;
    }

    .search-container {
      flex: 1;
      display: flex;
      align-items: center;
    }

    .search-box {
      flex: 1;
      height: 64rpx;
      background: #f5f5f5;
      border-radius: 32rpx;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      position: relative;
    }

    .clear-input {
      position: absolute;
      right: 20rpx;
    }

    .search-input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
      color: #333;
    }

    .search-button {
      margin-left: 16rpx;
    }

    .search-text {
      font-size: 28rpx;
      color: #333;
    }
  }

  .fill {
    height: 88rpx;
  }

  .search-section {
    padding: 20rpx 30rpx;
  }

  .section-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
    font-size: 32rpx;
    color: #333;
  }

  .clear-history {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30rpx;
  }

  .history-item {
    padding: 10rpx 20rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    background: #f5f5f5;
    border-radius: 10rpx;
    font-size: 28rpx;
    color: #333;
  }

  .refresh-icon {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .hot-books {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }

  .book-item {
    display: flex;
    align-items: center;
    padding: 10rpx;
    background: #fff;
    border-radius: 10rpx;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  }

  .book-rank {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: bold;
  }

  .book-cover {
    width: 100rpx;
    height: 140rpx;
    margin: 0 10rpx;
  }

  .cover-image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
  }

  .book-info {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .book-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 5rpx;
    word-wrap: break-word;
    overflow: hidden;
  }

  .book-search-count {
    font-size: 24rpx;
    color: #999;
  }

  /* 搜索框结果样式 */
  .search-results {
    padding: 20rpx 30rpx;
    overflow: hidden;
  }

  .search-results .book-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1px solid #f5f5f5;
  }

  .book-details {
    flex: 1;
    margin-left: 10rpx;
  }

  .book-title-rating {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
  }

  .book-rating {
    color: #ff6b6b;
    font-weight: bold;
  }

  .book-description {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .book-author {
    font-size: 24rpx;
    color: #999;
  }
}

/* 添加旋转动画 */
.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>    